package io.hxci.modules.tea.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.hxci.common.annotation.SysLog;
import io.hxci.common.oss.entity.ConstantProperties;
import io.hxci.common.oss.service.AliyunOSSUtil;
import io.hxci.common.utils.Constant;
import io.hxci.common.utils.PageUtils;
import io.hxci.common.utils.R;
import io.hxci.modules.sys.controller.AbstractController;
import io.hxci.modules.tea.domain.TeaDict;

import io.hxci.modules.tea.domain.TeaTreatise;
import io.hxci.modules.tea.service.TeaDictService;

import io.hxci.modules.tea.service.TeaTreatiseService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("tea/teatreatise")
public class TeaTreatiseController extends AbstractController {
    @Autowired
    private TeaTreatiseService teaTreatiseService;
    @Autowired
    private TeaDictService teaDictService;
    @Autowired
    private ConstantProperties constantProperties;
    @Autowired
    private AliyunOSSUtil aliyunOSSUtil;

    @SysLog("查看专著和主编教材")
    @RequestMapping("/query")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = teaTreatiseService.queryPage(params);
        return R.ok().put("page", page);
    }

    @SysLog("更新专著和主编教材")
    @RequestMapping("saveOrUpdate")
    public R save(@RequestBody TeaTreatise teaTreatise){
        if(teaTreatise.getUserId() == null){
            teaTreatise.setUserId(getUserId());
        }


        teaTreatiseService.saveOrUpdate(teaTreatise);
        return R.ok();
    }

    @SysLog("删除专著和主编教材")
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] id){
        teaTreatiseService.removeByIds(Arrays.asList(id));
        return R.ok();
    }

    @SysLog("编辑专著和主编教材")
    @RequestMapping("/edit/{id}/{type}")
    @ResponseBody
    public R edit(@PathVariable("id") Integer id,@PathVariable("type") String type){
        TeaTreatise edit = teaTreatiseService.getById(id);
        List<TeaDict> list = teaDictService.list(new QueryWrapper<TeaDict>().like(StringUtils.isNotBlank(type),"type", type));
        return R.ok().put("edit", edit).put("kdoptions",list);
    }

    @SysLog("编辑专著和主编教材佐证上传")
    @RequestMapping("/fileUpload")
    public R  fileUpload(HttpServletRequest request) throws IOException {
        long  startTime=System.currentTimeMillis();//获取当前时间
        MultipartHttpServletRequest multipartRequest =(MultipartHttpServletRequest) request;
        String  username = getUser().getUsername();
        String uploadUrl = "";

        MultipartFile file = multipartRequest.getFile("file"); // 通过参数名获取指定文件

        try {

            if (null != file) {
                String filename = file.getOriginalFilename();
                if (!"".equals(filename.trim())) {
                    File newFile = new File(filename);
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(file.getBytes());
                    os.close();
                    file.transferTo(newFile);
                    //上传到OSS
                    String fileName = UUID.randomUUID().toString().replace("-", "");
                    uploadUrl = aliyunOSSUtil.upload(newFile,"专著和主编教材",username,fileName);
               //     teaFileService.save(new TeaFile(null,fileName,"专著和主编教材", constantProperties.getEndpoint(),uploadUrl,username,null,null));
                }

            }


        }catch (Exception ex){
            ex.printStackTrace();
        }




//        String path = request.getContextPath();
//        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path;
//        String originalFilename =file.getOriginalFilename();
//
//        File filedir = new File(Constant.UPLOADURL+username);
//        if (!filedir.exists()) {
//            filedir.mkdirs();
//        }
//        String rpath=Constant.UPLOADURL+username+"/"+originalFilename;
//        File newFile=new File(rpath);
//        file.transferTo(newFile);
//        long  endTime=System.currentTimeMillis();
//        System.out.println("上传方法的运行时间："+String.valueOf(endTime-startTime)+"ms");
        //System.out.println("上传路径："+basePath+"/statics/image/"+originalFilename);
        return R.ok().put("photoPath", uploadUrl);
    }
}
